package com.mashibing.juc.c_019;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock用于代替synchronized
 *
 * 使用ReentrantLock需要手动解锁
 * 遇到异常时synchronized会自动释放锁，但是ReentrantLock需要手动释放
 * @author: Yuanzt
 * @Date: 2021/3/26
 */
public class T03_ReentrantLock3 {

    Lock lock = new ReentrantLock();
    void m1(){
        try {
            lock.lock();//用于替代synchronized(this)
            for (int i = 0; i < 3; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 使用tryLock进行尝试锁定，不管锁定与否方法都会继续执行
     * 可以根据trylock的返回值来判断是否锁定
     * 也可以指定tryLock的时间，由于tryLock(time)抛出异常，在unlock的时候需要判断
     */
    void m2(){
        boolean locked = false;
        try {
            locked = lock.tryLock(5,TimeUnit.SECONDS);
            System.out.println("m2..." + locked);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (locked) lock.unlock();
        }
    }

    public static void main(String[] args) {
        T03_ReentrantLock3 tr = new T03_ReentrantLock3();
        new Thread(tr::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(tr::m2).start();

    }
}
